package com.wsm.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.wsm.common.config.BaseConfig;
import com.wsm.common.config.CloseConfig;
import com.wsm.common.enums.CloseKey;
import com.wsm.common.enums.ConfigKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @name: SmsUtils
 * @Author: wangshimin
 * @Date: 2020/2/7  11:27
 * @Description:阿里云短信
 */
@Slf4j
@Component
public class SmsUtils {

    public enum SMS_MODEL {
        //springboot工程：您的验证码${code}，该验证码5分钟内有效，请勿泄漏于他人
        ValidateCOde("餐饮管理平台", "SMS_182674228", new String[]{"code"}),
        //尊敬的${name},您已成功注册springBoot博客。账号为${userName},请尽快登录网站修改。网址：www.wangshimin.top
        Notice("餐饮管理平台", "SMS_183245425", new String[]{"name", "userName"});

        private String signName;
        private String templateCode;
        private String[] templateParam;

        SMS_MODEL(String signName, String templateCode, String[] templateParam) {
            this.signName = signName;
            this.templateCode = templateCode;
            this.templateParam = templateParam;
        }

        public String getSignName() {
            return signName;
        }

        public void setSignName(String signName) {
            this.signName = signName;
        }

        public String getTemplateCode() {
            return templateCode;
        }

        public void setTemplateCode(String templateCode) {
            this.templateCode = templateCode;
        }
    }

    @Autowired
    CloseConfig closeConfig;
    @Autowired
    BaseConfig baseConfig;

    //发送注册验证码信息
    @Async("asyncSendSMSExecutor")
    public void sendSms(String phoneNum, SMS_MODEL sms_model, Map<String, Object> sendMap, String outId) {
        if (!closeConfig.getMap(CloseKey.SMS.getValue())) {
            return;
        }
        Object map = baseConfig.getMap(ConfigKey.SMS.getValue());
        if (null == map) {
            log.error("未配置Sms信息，无法发送短信");
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(map.toString());
        String product = jsonObject.get("product").toString();
        String domain = jsonObject.get("domain").toString();
        String accessKeyId = jsonObject.get("accessKeyId").toString();
        String accessKeySecret = jsonObject.get("accessKeySecret").toString();
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            log.info("[阿里云短信接口] 发送 手机号码为：{} 的注册验证短信失败", phoneNum);
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNum);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(sms_model.getSignName());
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(sms_model.getTemplateCode());
        //可选:模板中的变量替换JSON串
        request.setTemplateParam(JSONUtils.beanToJson(sendMap));
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        if (!StringUtils.isEmpty(outId)) {
            request.setOutId(outId);
        }
        //hint 此处可能会抛出异常，注意catch
        try {
            SendSmsResponse acsResponse = acsClient.getAcsResponse(request);
            log.info(JSONUtils.beanToJson(acsResponse));
            log.info("Code=" + acsResponse.getCode());
            log.info("Message=" + acsResponse.getMessage());
            log.info("RequestId=" + acsResponse.getRequestId());
            log.info("BizId=" + acsResponse.getBizId());
            log.info("[阿里云短信接口] 发送 手机号码为：{} 的注册验证短信成功,通知内容为：{}", phoneNum, JSONUtils.beanToJson(sendMap));
        } catch (ClientException e) {
            log.info("[阿里云短信接口] 发送 手机号码为：{} 的注册验证短信失败", phoneNum);
        }

    }


    //发送信息
    @Async("asyncSendSMSExecutor")
    public void sendNoticeSms(String phoneNum, SMS_MODEL sms_model, Map<String, Object> sendMap, String outId) {
        if (!closeConfig.getMap(CloseKey.SMS.getValue())) {
            return;
        }
        Object map = baseConfig.getMap(ConfigKey.SMS.getValue());
        if (null == map) {
            log.error("未配置Sms信息，无法发送短信");
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(map.toString());
        String product = jsonObject.get("product").toString();
        String domain = jsonObject.get("domain").toString();
        String accessKeyId = jsonObject.get("accessKeyId").toString();
        String accessKeySecret = jsonObject.get("accessKeySecret").toString();
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            log.info("[阿里云短信接口] 发送 手机号码为：{} 的注册通知短信失败", phoneNum);
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNum);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(sms_model.getSignName());
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(sms_model.getTemplateCode());
        //可选:模板中的变量替换JSON串
        request.setTemplateParam(JSONUtils.beanToJson(sendMap));
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        if (!StringUtils.isEmpty(outId)) {
            request.setOutId(outId);
        }
        //hint 此处可能会抛出异常，注意catch
        try {
            SendSmsResponse acsResponse = acsClient.getAcsResponse(request);
            /*log.info(JSONUtils.beanToJson(acsResponse));
            log.info("Code=" + acsResponse.getCode());
            log.info("Message=" + acsResponse.getMessage());
            log.info("RequestId=" + acsResponse.getRequestId());
            log.info("BizId=" + acsResponse.getBizId());*/
            if (null != acsResponse.getBizId()) {
                log.info("[阿里云短信接口] 发送 手机号码为：{} 的注册通知短信成功,注册内容为：{}", phoneNum, JSONUtils.beanToJson(sendMap));
            } else {
                log.info("[阿里云短信接口] 发送 手机号码为：{} 的注册通知短信失败", phoneNum);
            }
        } catch (ClientException e) {
            log.info("[阿里云短信接口] 发送 手机号码为：{} 的注册通知短信失败", phoneNum);
        }
    }

    //查询
    public QuerySendDetailsResponse querySendDetails(String bizId, String phoneNum) throws ClientException {
        Object map = baseConfig.getMap(ConfigKey.SMS.getValue());
        if (null == map) {
            log.error("未配置Sms信息，无法发送短信");
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(map.toString());
        String product = jsonObject.get("product").toString();
        String domain = jsonObject.get("domain").toString();
        String accessKeyId = jsonObject.get("accessKeyId").toString();
        String accessKeySecret = jsonObject.get("accessKeySecret").toString();
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber(phoneNum);
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        request.setSendDate(DateUtils.format(new Date(), "yyyyMMdd"));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);
        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        System.out.println("短信明细查询接口返回数据----------------");
        System.out.println("Code=" + querySendDetailsResponse.getCode());
        System.out.println("Message=" + querySendDetailsResponse.getMessage());
        int i = 0;
        for (QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs()) {
            System.out.println("SmsSendDetailDTO[" + i + "]:");
            System.out.println("Content=" + smsSendDetailDTO.getContent());
            System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
            System.out.println("OutId=" + smsSendDetailDTO.getOutId());
            System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
            System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
            System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
            System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
            System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
        }
        System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
        System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
        return querySendDetailsResponse;
    }
}
